import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'
// 专门持久化存储 vuex 中数据的第三方包
import Vuexpersistedstate from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({
  plugins: [Vuexpersistedstate()],
  state: {
    token: '',
    userInfo: {}
    // token: localStorage.getItem('token') || ''
  },
  mutations: {
    updateToken (state, token) {
      state.token = token
      // localStorage.setItem('toekn', token)
    },
    updateUserInfo (state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    // 处理用户最新信息
    async getUserInfo (context) {
      const { data: res } = await axios.get('/my/userinfo', {
        headers: {
          Authorization: context.state.token
        }
      })
      // console.log(res)
      if (res.code === 0) {
        context.commit('updateUserInfo', res.data)
      }
    }
  },
  modules: {}
})
